<template>
  <div class="app-container">
    <!-- 公共顶部 -->
    <large-screen-header />
    <!-- 主体部分 -->
    <div class="app-main">
      <!-- 左侧 -->
      <div class="app-left">
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'全国89年后5级以上地震数量和灾评次数'" />
          <!-- echarts统计 -->
          <NumberDisater :data="earthquakesNumberdisaster" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'灾评次数前五省份'" />
          <Liveness :data="abProvinceActivationRank" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'近五次地震灾害各类损失占比'" />
          <LineCharts :listData="getLossProportionRank" />
        </div>
      </div>

      <!-- 中心部分 -->
      <div class="app-center">
        <!-- 标题 -->
        <headline :name="'全国地震灾害损失评估结果'" />
        <!-- 地图 -->
        <div class="app-map">
          <SystemSelect :styles="{ position: 'absolute', top: '-30px', left: '42px' }" />
          <!-- <IndexMap></IndexMap> -->
          <Legend :style="{ bottom: '150px' }" startColor="#ffffff" endColor="#A80000"></Legend>
          <OlMap :refId="'lossassessment'" style="height: 100%" @getMap="getMap" @mapClick="mapClick"></OlMap>
          <div ref="popupElement" class="popup-bg" id="map-popup">
            <div class="triangle"></div>
            <div class="popup-head">
              <div class="popup-head-title">{{ tableData.name }}历年来地震灾损情况表</div>
              <div class="popup-head-x" style="cursor: pointer" @click="hidePopup()">X</div>
            </div>
            <div class="popup-content">
              <div class="popup-table">
                <el-table max-height="150" :data="tableData.list">
                  <el-table-column prop="originTime" label="发震时间" :header-align="headerAlign">
                    <template #default="scope">
                      <div class="centered-cell">{{ scope.row.originTime }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="magnitude" label="震级" :header-align="headerAlign">
                    <template #default="scope">
                      <div style="color: #46ffff" class="centered-cell">{{ scope.row.magnitude }}</div>
                    </template>
                  </el-table-column>
                  <el-table-column prop="lossValue" label="损失值" :header-align="headerAlign">
                    <template #default="scope">
                      <div style="color: #46ffff" class="centered-cell">{{ scope.row.lossValue }}</div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </div>
        </div>
      </div>
      <!-- 右侧 -->
      <div class="app-right">
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'评估参与单位'" />
          <UnitStatistics v-if="isUnitCountRankValue" :data="getUnitCountRank" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'累计损失值前五省份'" />
          <DamageValueChart :listData="DamageValueRank" />
        </div>
        <div class="app-left-item">
          <!-- 次级标题 -->
          <subheadings :name="'地震现场灾害损失评估访问统计'" />
          <!-- <AccessStatistics/> -->
          <AccessStatistics v-if="isShow" :listData="SystemAchievementsStatistics" />
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import NumberDisater from './components/NumberDisater.vue';
import Liveness from './components/Liveness.vue';
import UnitStatistics from './components/UnitStatistics.vue';
import LineCharts from './components/LineCharts.vue';
import DamageValueChart from './components/DamageValueChart.vue';
import AccessStatistics from './components/AccessStatistics.vue';
// 系统选择
import SystemSelect from '@/components/SystemSelect';
import {
  getDamageNum,
  getDisasterNum,
  getLossProportion,
  getUnitCount,
  getVisitNum,
  getDisasterValue,
  getMapDate,
  getCountyDisasterByCountyCode,
} from '@/api/lossAssessment.js';
// start
import OlMap from '@/components/Olmap';
import { Style, Circle as CircleStyle, Fill, Stroke, Icon, Text } from 'ol/style';
import { Feature } from 'ol';
import WKT from 'ol/format/WKT';
import { Point } from 'ol/geom';
import { Vector as VectorLayer } from 'ol/layer';
import { Vector as VectorSource } from 'ol/source';
import yellowEllipse from '@/assets/map/image/newImage/ellipse487.png';
import Overlay from 'ol/Overlay';
import { GeoJSON as GeoJSonFormat } from 'ol/format';
import Legend from './components/Legend.vue';
import { getChinaBaseMap, getBaseDir } from '@/map/projMap.js';
import { convertToGeoJSON } from '@/utils/map.js';
import { useRouter } from 'vue-router';
// end
// start
const router = useRouter();
const tableData = reactive({
  name: '',
  list: [],
});
const mapInstance = ref(null);
const vectorLayer = ref(null);
const mapPopupLayer = ref(null);
const popupElement = ref();
const headerAlign = 'center'; // 设置表头的对齐方式为居中
// end
//全国5级以上地震数量和灾害评估数量
const earthquakesNumberdisaster = ref([]);
// 灾损数量前五省份
const abProvinceActivationRank = ref([]);
//近五次地震灾害各类损失占比
const getLossProportionRank = ref([]);
//灾评单位统计
const getUnitCountRank = ref([]);
//灾损值前五省份
const DamageValueRank = ref([]);
// 地震灾害损失评估访问统计
const SystemAchievementsStatistics = ref([]);
const isShow = ref(false);
const isUnitCountRankValue = ref(false);
getData();
function getData() {
  //全国5级以上地震数量和灾害评估数量
  getDisasterNum().then((res) => {
    earthquakesNumberdisaster.value = res.data;
  });
  // 灾损数量前五省份
  getDamageNum().then((res) => {
    abProvinceActivationRank.value = res.data;
  });
  //近五次地震灾害各类损失占比
  getLossProportion().then((res) => {
    getLossProportionRank.value = res.data;
  });
  //   灾评单位统计
  getUnitCount().then((res) => {
    getUnitCountRank.value = res.data;
    isUnitCountRankValue.value = true;
  });
  //灾损值前五省份
  getDisasterValue().then((res) => {
    DamageValueRank.value = res.data;
  });
  // // 地震灾害损失评估访问统计
  getVisitNum({ system: 0 }).then((res) => {
    SystemAchievementsStatistics.value = res.data;
    isShow.value = true;
  });
}
// start

const getMap = (map) => {
  mapInstance.value = map.value;
  console.log('jjj', mapInstance.value);

  addProvinceNameLayer();
  // addPolygonLayer();
  getMapData();
  //   假数据
  createVectorLayer();
  createPopUpLayer();
};

function addProvinceNameLayer() {
  const geojsonSource = new VectorSource({
    url: getChinaBaseMap,
    format: new GeoJSonFormat(),
  });

  // 创建省份名称文本图层
  const textLayer = new VectorLayer({
    source: geojsonSource,
    zIndex: 3,
    style: function (feature) {
      const textstyle = new Style({
        text: new Text({
          font: '10px Calibri,sans-serif',
          fill: new Fill({ color: '#fff' }),
          text: feature.get('name'),
        }),
      });
      return textstyle;
    },
  });

  mapInstance.value.addLayer(textLayer);
}
const getMapData = () => {
  getMapDate().then((res) => {
    console.log('res---', res);
    if (res.code == 200) {
      let data = res.data;
      addRandomPoints(data);
      addPolygonLayer(data);
    }
  });
};

function addPolygonLayer(data) {
  let features = [];
  data.list.forEach((item) => {
    let featureTmp = new WKT().readFeature(item.geom);
    featureTmp.set('area', item.area);
    featureTmp.set('county', item.county);
    featureTmp.set('countyCode', item.countyCode);
    featureTmp.set('id', item.id);
    featureTmp.set('type', 2);
    featureTmp.setStyle(
      new Style({
        fill: new Fill({
          color: getColorByArea(item.area),
        }),
        stroke: new Stroke({
          color: 'red',
          width: 1,
        }),
      })
    );
    features.push(featureTmp);
  });
  //
  // let geojson = convertToGeoJSON(data.list);
  // const geojsonFormat = new GeoJSonFormat();
  // let features = geojsonFormat.readFeatures(geojson);
  console.log('features--', features);
  // features.forEach((feature) => {

  // });
  function getColorByArea(area) {
    // const colors = {
    //   6: 'rgba(255,190,190,0.7)',
    //   7: 'rgba(255,127,127,0.7)',
    //   8: 'rgba(200,40,40,0.7)',
    //   9: 'rgba(168,0,0,0.7)',
    //   10: 'rgba(140,0,0,0.7)',
    // };
    // console.log('color0---', area, colors[area]);
    // return colors[area];
    // 定义颜色范围
    const startColor = [255, 255, 255, 1]; // rgba(255, 170, 170, 1)
    const endColor = [168, 0, 0, 1]; // rgba(168, 0, 0, 1)

    // 对 area 进行范围限制，确保在 0.0 到 1.0 之间
    area = Math.min(1, Math.max(0, parseFloat(area).toFixed(1)));

    // 计算每个颜色通道的差值
    const colorDiff = endColor.map((endValue, index) => {
      return endValue - startColor[index];
    });

    // 根据 area 计算颜色值
    const color = startColor.map((startValue, index) => {
      return Math.round(startValue + colorDiff[index] * area);
    });
    // 构造 rgba 颜色字符串
    return `rgba(${color.join(', ')})`;
  }

  const vectorLayer = new VectorLayer({
    source: new VectorSource(),
    zIndex: 4,
  });
  vectorLayer.getSource().addFeatures(features);

  mapInstance.value.addLayer(vectorLayer);
}

const mapClick = async (event) => {
  const features = mapInstance.value.getFeaturesAtPixel(event.pixel);
  if (features.length > 0) {
    let selectedFeature = features.find((feature) => feature.get('id') == 'point');
    if (selectedFeature) {
      router.push('/intensityAssessment');
      return;
    }
    selectedFeature = features.find((feature) => feature.get('type') == 2);
    if (!selectedFeature) {
      mapPopupLayer.value.setPosition(undefined);
      return;
    }
    tableData.name = selectedFeature.get('county');
    let countyCode = selectedFeature.get('countyCode');
    let res = await getCountyDisasterByCountyCode({ countyCode });
    console.log('res---', res);
    tableData.list = res.data;
    let coordinate = mapInstance.value.getEventCoordinate(event.originalEvent);
    /**const coordinate = selectedFeature.getGeometry().getCoordinates();
    mapPopupLayer.value.setPosition(coordinate);
    // 获取地图容器的尺寸和点击事件的位置
    const mapContainerRect = mapInstance.value.getTarget().getBoundingClientRect();
    const clickX = event.pixel[0];
    const clickY = event.pixel[1];

    // 获取弹出框的尺寸
    const popupWidth = popupElement.value.offsetWidth;
    const popupHeight = popupElement.value.offsetHeight;

    // 默认的 positioning
    let positioning = 'top-left';

    // 判断弹出框是否超出地图容器的各个边界
    if (clickX + popupWidth > mapContainerRect.width) {
      positioning = 'top-right';
    } else if (clickX - popupWidth < 0) {
      positioning = 'top-left';
    }

    if (clickY + popupHeight > mapContainerRect.height) {
      positioning = positioning.replace('top', 'bottom');
    } else if (clickY - popupHeight < 0) {
      positioning = positioning.replace('bottom', 'top');
    }

    // 设置弹出框的位置和定位方式
    mapPopupLayer.value.setPositioning(positioning);
*/
    // 设置弹出框的位置
    mapPopupLayer.value.setPosition(coordinate);
    // 在这里添加处理点击事件的逻辑
    console.log('点击了要素：', selectedFeature.getProperties());
  } else {
    mapPopupLayer.value.setPosition(undefined);
  }
};
const createVectorLayer = () => {
  vectorLayer.value = new VectorLayer({
    source: new VectorSource(),
    zIndex: 6,
  });
  mapInstance.value.addLayer(vectorLayer.value);
};
const addRandomPoints = (data) => {
  if (!vectorLayer.value) {
    return;
  }

  const point = new Feature({
    geometry: new Point([parseFloat(data.longitude), parseFloat(data.latitude)]),
  });
  point.set('id', 'point');
  point.set('countyCode', data.countyCode);
  const style = new Style({
    image: new Icon({
      src: yellowEllipse,
      scale: 1,
    }),
  });

  point.setStyle(style);
  vectorLayer.value.getSource().addFeature(point);
};
const createPopUpLayer = () => {
  let popup = document.getElementById('map-popup');
  mapPopupLayer.value = new Overlay({
    element: popup,
    positioning: 'center-left',
    offset: [10, 0], // 偏移量，可根据需要进行调整
  });
  mapInstance.value.addOverlay(mapPopupLayer.value);
};

function hidePopup() {
  mapPopupLayer.value.setPosition(undefined);
}

// end
</script>

<style scoped lang="scss">
.app-map {
  width: 960px;
  height: 100%;
  overflow: visible;
}
.app-main {
  display: flex;
  justify-content: space-between;
  .app-left {
    margin-left: 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;

    &-item {
      width: 450px;
      height: 300px;
      // background: linear-gradient(135deg, #00032D 0%, #000C58 50%, #00032D 100%);
      // opacity: .85;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      color: #fff;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 20px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
      &:nth-child(2) {
        height: 260px;
      }
      &:nth-child(3) {
        height: 320px;
      }
    }
  }
  .app-right {
    margin-right: 30px;
    margin-top: 10px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100% - 40px);
    width: 450px;

    &-item {
      width: 450px;
      height: 300px;
      background: linear-gradient(
        135deg,
        rgba(0, 3, 45, 0.85) 0%,
        rgba(0, 12, 88, 0.85) 50%,
        rgba(0, 3, 45, 0.85) 100%
      );
      position: relative;
      &::after {
        content: '';
        display: block;
        width: 450px;
        height: 50px;
        background-size: 100% 100%;
        background-image: url('../../assets/images/common/bg_bottom.png') !important;
        position: absolute;
        bottom: -10px;
      }
      &:nth-child(2) {
        height: 260px;
      }
      &:nth-child(3) {
        height: 320px;
      }
    }
  }
}

/* start */
.popup-bg {
  width: 400px;
  height: 275px;
  /* background: linear-gradient(NaNdeg, rgba(5, 12, 53, 0.8) 0%, rgba(4, 16, 89, 0.8) 55%, rgba(6, 40, 150, 0.8) 100%); */
  background: rgba(6, 40, 150, 0.8);
  border-radius: 8px 8px 8px 8px;
  opacity: 1;
  border: 2px solid #0190f9;
  display: flex;
  padding: 17px 15px;
  flex-direction: column;
  position: relative;
  .triangle {
    position: absolute;
    top: 50%;
    left: -10px;
    transform: translateY(-50%);
    width: 0;
    height: 0;
    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-right: 10px solid #0190f9;
  }
  .popup-head {
    justify-content: center;

    display: flex;
    flex-direction: row;
    font-size: 18px;
    font-family: Source Han Sans CN-Bold, Source Han Sans CN;
    font-weight: bold;
    color: #ffffff;
    line-height: 23px;
    .popup-head-title {
      margin-left: auto;
    }
    .popup-head-x {
      margin-left: auto;
      width: 12px;
      height: 12px;
      color: #e6f4fd;
      opacity: 1;
    }
  }
  .popup-content {
    height: 100%;
    margin-top: 16px;
    display: flex;
    flex-direction: column;
    font-size: 16px;
    font-family: Source Han Sans CN-Medium, Source Han Sans CN;
    font-weight: 500;
    color: #e6f4fd;
    line-height: 23px;
    .popup-content-title {
      background: #050426;
      border-radius: 0px 0px 0px 0px;
      opacity: 0.5;
      padding: 10px 34px;
      justify-content: space-between;
      display: flex;
      flex-direction: row;
    }
    .popup-table {
      width: 100%;
      height: 100%;
      margin-right: 20px;
      .centered-cell {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }
      .el-table {
        width: 90%;
        max-height: 150px;
        overflow-x: hidden;
        overflow-y: auto;
        z-index: 99;
        position: absolute;
        /* background: linear-gradient(135deg, #00032d 0%, #000c58 50%, #00032d 100%); */
        /* 背景透明 */
        background: rgba(0, 0, 0, 0);
        :deep(tr:hover > td) {
          background: rgba(71, 90, 219, 0.05) !important;
        }
        // top: 70px;
        // background-color: #00032D;
        /* background: linear-gradient(135deg, #00032d 0%, #000c58 50%, #00032d 100%); */
        :deep(.el-table__header) {
          background: rgba(5, 4, 38, 0.4);
          tr {
            background-color: transparent !important;
          }
          th.el-table__cell {
            background-color: transparent !important;
          }
          th.el-table__cell.is-leaf {
            border-bottom: none;
          }
        }

        :deep(.el-table__row) {
          background: rgba(5, 4, 38, 0.4);
        }
        :deep(.el-table__inner-wrapper)::before {
          display: none;
        }
      }
    }
  }
}
/**
.popup-bg::before {
  content: '';
  width: 0;
  height: 0;
  border: 15px solid;
  position: absolute;
  top: 50%;
  left: -35px;
  margin-top: -15px;
  border-color: transparent rgb(1, 144, 249, 0.8) transparent transparent;
}
.popup-bg:after {
  content: '';
  width: 0;
  height: 0;
  border: 15px solid;
  position: absolute;
  top: 50%;
  left: -33px;
  margin-top: -15px;
  border-color: transparent rgba(6, 40, 150, 0.8) transparent transparent;
} 
*/
:deep(.ol-overlaycontainer-stopevent) {
  z-index: 2;
}
/* end */
</style>
